package com.qk.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qk.Response.PageResult;
import com.qk.domain.user.UserDO;
import com.qk.dto.UserDTO;
import com.qk.entity.Role;
import com.qk.enums.ParamEnum;
import com.qk.mapper.RoleMapper;
import com.qk.utils.JwtUtils;
import com.qk.vo.user.UserLoginVO;
import com.qk.entity.User;
import com.qk.exception.CommonException;
import com.qk.mapper.UserMapper;
import com.qk.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    //默认密码后缀
    private static final String DEFAULT_PASSWORD_SUFIX = "123";
    private static final Integer NORMAL_USER_STATUS = 1;
    private static final Integer UNNORMAL_USER_STATUS = 0;
    @Override
    public PageResult<UserDO> getUsers(UserDTO userDto) {
        //参数校验
        userDto.checkPageParam();
        PageHelper.startPage(userDto.getPage(),userDto.getPageSize());
        List<UserDO> users = userMapper.selectPageUsers(userDto);
        PageResult<UserDO> pageResult = new PageResult<>();
        PageInfo<UserDO> userPageInfo = new PageInfo<>(users);
        pageResult.setTotal(userPageInfo.getTotal());
        pageResult.setRows(userPageInfo.getList());
        return pageResult;
    }

    @Override
    public void addUser(UserDO userDO) {
        //参数校验
        //工具类处理参数校验 Hutool
        boolean isNull=BeanUtil.hasNullField(userDO,"id","password","deptId","roleId","image","remark","createTime","updateTime");
        if (!isNull){
            throw new RuntimeException("参数不能为空");
        }
        //密码加密  MD5加密
        //拼接密码
        String  rowPassword=new StringBuilder().append(userDO.getPassword()).append(DEFAULT_PASSWORD_SUFIX).toString();
        //MD5加密写入数据库
        String password = DigestUtils.md5DigestAsHex(rowPassword.getBytes());
        userDO.setPassword(password);
        userDO.setCreateTime(LocalDateTime.now());
        userDO.setUpdateTime(LocalDateTime.now());
        userMapper.addUser(userDO);
    }

    @Override
    public UserDO getUserById(Integer id) {
        if (id == null || id < 1) {
            throw new RuntimeException("参数不能为空");
        }
        return userMapper.getUserById(id);
    }

    @Override
    public void updateUser(UserDO userDO) {
        //参数校验
        boolean isNull = Objects.isNull(userDO);
        if (isNull){
            throw new RuntimeException("参数不能为空");
        }
        userDO.setUpdateTime(LocalDateTime.now());
        userMapper.updateUser(userDO);

    }

    @Override
    public Object getAllUsers() {
        List<User> users = userMapper.getAllUsers();
        return users;
    }

    @Override
    public Object getUsersByRole(String lable) {
        //参数校验
        if (lable == null || lable.length() < 1) {
            throw new RuntimeException("参数不能为空");
        }
        List<User> users = userMapper.getUsersByRole(lable);
        return  users;
    }

    @Override
    public void deleteUsers(List<Integer> ids) {
        //参数校验
        if (ids == null || ids.size() < 1) {
            throw new RuntimeException("参数不能为空");
        }
        userMapper.deleteUsers(ids);

    }

    @Override
    public Object getUsersByDeptId(Integer deptId) {
        //参数校验
        if (deptId == null || deptId < 1) {
            throw new RuntimeException("参数不能为空");
        }
        List<User> users = userMapper.getUsersByDeptId(deptId);
        return  users;
    }

    @Override
    public UserLoginVO login(String username, String password) {
        //参数校验  trim()去除空格
        if (username == null || username.trim().isEmpty() || password == null || password.trim().isEmpty()) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        // 查询用户信息
        //通过用户名查询用户信息并和数据库中的密码进行比较
        User user = userMapper.selectByUsername(username);
        if (Objects.isNull( user)){
            CommonException.throwCommonException(ParamEnum.USER_NOT_EXIST);
        }
        // 校验用户状态
        if (ObjectUtil.equals(user.getStatus(),  UNNORMAL_USER_STATUS)){
            CommonException.throwCommonException(ParamEnum.USER_NOT_NORMAL);
        }
        //密码校验
        String userPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        String encodePassword = user.getPassword();
        boolean isChecked = ObjectUtil.equals(userPassword, encodePassword);
        if (!isChecked){
            CommonException.throwCommonException(ParamEnum.USER_NAME_PASSORD_ERROR);
        }
        // 获取用户角色信息
        Role role = roleMapper.selectRoleById(user.getRoleId());
        // 生成JWT
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("username", user.getUsername());
        String jwt = JwtUtils.generateToken(claims);
        // 组装返回结果
       return UserLoginVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .name(user.getName())
                .image(user.getImage())
               //todo 角色标签 待处理  方式一：多表关联查询  方式二：通过角色id查询角色名称
                .roleLabel(role.getName())
                .token(jwt)
                .build();
    }
}
